//
//  LTCityViewController.m
//  LocalTravel
//
//  Created by zheng ji on 14-3-15.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "LTCityViewController.h"
#import "LTAppDelegate.h"
@interface LTCityViewController ()
{
    NSArray* _arrayProvince;
    NSMutableArray* _citySearchArray;
    BOOL isSearch;
}
@end

@implementation LTCityViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    isSearch=NO;
 
  
   // [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse_cell"];
    [self initCityData];
    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 250, 30)];
 
    searchBar.placeholder=@"输入城市拼音或者中文";
    searchBar.delegate=self;
 
    UIBarButtonItem* item=[[UIBarButtonItem alloc]initWithCustomView:searchBar];
    // searchBar.delegate = self;
    self.navigationItem.rightBarButtonItem=item;
    item=nil;
    searchBar=nil;
    
    
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
   // self.tableView.allowsSelection = YES;
    //self.tableView.scrollEnabled = YES;
    [searchBar resignFirstResponder];   //隐藏输入键盘
    
    
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    NSLog(@"searchBarTextDidEndEditing");
    [self searchCity:searchText];
    

}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    NSLog(@"searchBarCancelButtonClicked");
}


-(void)initCityData{
    
    LTAppDelegate* appDelegate=(LTAppDelegate*)[[UIApplication sharedApplication] delegate];
    _arrayProvince=[appDelegate getProvinceData];
    appDelegate=nil;
    /*
    NSString* file=[[NSBundle mainBundle] pathForResource:@"citys" ofType:@"json"];
    NSError* error=nil;
   NSDictionary *dictionary= [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:file] options:kNilOptions error:&error];
    if(!error){
        
        
        NSDictionary *dict=[dictionary objectForKey:@"provincelist"];
        if(dict !=nil && dict.count>0){
            _arrayProvince=[dict objectForKey:@"province"];
           
        }
        
    
    }
     */
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
 
    if(!isSearch && _arrayProvince !=nil){
        return _arrayProvince.count;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger ret=0;
    if(isSearch && _citySearchArray !=nil){
        ret=_citySearchArray.count;
    }else{
      if(_arrayProvince !=nil && _arrayProvince.count>=section){
        
          NSDictionary* dict=[_arrayProvince objectAtIndex:section];
        
          NSDictionary* dict2=[dict objectForKey:@"cityList"];
        
          NSObject* obj=[dict2 objectForKey:@"city"];
          if([obj isKindOfClass:[NSDictionary class]]){
            
            ret=1;
          }else if([obj isKindOfClass:[NSArray class]]){
            NSArray* array=[dict2 objectForKey:@"city"];
               ret=array.count;
        }
        
        obj=nil;
        dict2=nil;
        dict=nil;
      }
    }
    return ret;
}
-(BOOL) searchInDictionary:(NSDictionary*)dict keyWord:(NSString*)keyWord{
    NSString* name=[dict objectForKey:@"name"];
    NSString* pinyin=[dict objectForKey:@"pinyin"];
    
    if([name hasPrefix:keyWord] || [pinyin hasPrefix:keyWord]){
        return YES;
    }
    return NO;
}
/**
 搜索城市名称或者拼音
 */
-(void)searchCity:(NSString*)keyWord{
    if(_arrayProvince==nil) return ;
    
    if(keyWord !=nil && ![keyWord isEqualToString:@""]){
       isSearch=YES;
        
        keyWord=[keyWord lowercaseString];
        _citySearchArray=[[NSMutableArray alloc]init];
        
        for (NSDictionary* dictProvince in _arrayProvince) {
            NSDictionary* dictCityList=[dictProvince objectForKey:@"cityList"];
            NSObject* obj=[dictCityList objectForKey:@"city"];
            if([obj isKindOfClass:[NSDictionary class]]){
                //ret=[dict2 objectForKey:@"city"];
                if([self searchInDictionary:[dictCityList objectForKey:@"city"] keyWord:keyWord]){
                    [_citySearchArray addObject:[dictCityList objectForKey:@"city"]];
                }
            }else if([obj isKindOfClass:[NSArray class]]){
                NSArray* array=[dictCityList objectForKey:@"city"];
                
                for (NSDictionary* dictCity in array) {
                    if([self searchInDictionary:dictCity  keyWord:keyWord]){
                        [_citySearchArray addObject:dictCity];
                    }
                }
                
            }
            
            
        }

        
    }else{
        isSearch=NO;
    }
    
    
    [self.tableView reloadData];
}
-(NSDictionary*)getCityDictionary:(NSInteger)section row:(NSInteger)row{
    NSDictionary* ret=nil;
    if(_arrayProvince !=nil && _arrayProvince.count>=section){
        
        NSDictionary* dict=[_arrayProvince objectAtIndex:section];
        
        NSDictionary* dict2=[dict objectForKey:@"cityList"];
        
        NSObject* obj=[dict2 objectForKey:@"city"];
        if([obj isKindOfClass:[NSDictionary class]]){
             ret=[dict2 objectForKey:@"city"];
        }else if([obj isKindOfClass:[NSArray class]]){
            NSArray* array=[dict2 objectForKey:@"city"];
            
            ret=[array objectAtIndex:row];
            array=nil;
        }
        
        obj=nil;
        dict2=nil;
        dict=nil;
    }
    
    return ret;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"reuse_cell";
    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
 
    NSDictionary* dictCity=nil;
    if(isSearch){
        if(_citySearchArray !=nil && _citySearchArray.count>indexPath.row){
            dictCity=[_citySearchArray objectAtIndex:indexPath.row];
        }
        
    }else{
         dictCity=[self getCityDictionary:indexPath.section row:indexPath.row];
      
    }
    if(dictCity!=nil){
        
        cell.textLabel.text=[NSString stringWithFormat:@"%@ %@",[dictCity objectForKey:@"index"],[dictCity objectForKey:@"name"]];
    }
    
    return cell;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
   NSString* text=@"";
    if(isSearch){
        text=@"搜索结果";
    }else{
      if(_arrayProvince !=nil && _arrayProvince.count>=section){
        
        text= [NSString stringWithFormat:@"%@ %@",[[_arrayProvince objectAtIndex:section] objectForKey:@"index"],[[_arrayProvince objectAtIndex:section] objectForKey:@"name"]];
        
      }
    }
    
    UILabel* lblHeader=[[UILabel alloc] init];
    lblHeader.font=[UIFont systemFontOfSize:18];
    lblHeader.textColor=[UIColor blueColor];
    lblHeader.backgroundColor=[UIColor colorWithRed:192.0/255.0f green:192.0f/255.0f blue:192.0f/255.0f alpha:0.5];
    lblHeader.text=text;
    return lblHeader;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if(self.delegate==nil) return ;
    
    NSDictionary* dictCity=nil;
    if(isSearch){
        if(_citySearchArray !=nil && _citySearchArray.count>=indexPath.row){
            dictCity=[_citySearchArray objectAtIndex:indexPath.row];
        }
    }else{
       dictCity=[self getCityDictionary:indexPath.section row:indexPath.row];
    }
    if(dictCity !=nil){
        [self.delegate citySelected:[dictCity objectForKey:@"id"] cityName:[dictCity objectForKey:@"name"]];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    
}


@end
